package 网络编程.Text;

import org.w3c.dom.Text;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UDPText1 {
    public static void main(String[] args) throws IOException {
        /**
         * 按照下面的要求实现程序
         * UDP发送数据:数据来自键盘录入，直到输入的数据是886，发送数据结束
         * UDP接收数据:因为接收端不知道发送端什么时候停止发送，故采用死循环接收
         */
        //创建发送端
        DatagramSocket ds=new DatagramSocket();
        //打包数据
        boolean judge=true;
        while (judge){
            Scanner scanner=new Scanner(System.in);
            System.out.print("请你输入要发送的内容:");
            String Receive=scanner.next();
            if (Receive.equals("886")){
                break;
            }
            byte[] bytes = Receive.getBytes();
            //指定ip
            InetAddress ByName = InetAddress.getByName("127.0.0.1");
            //端口号
            int port=18895;
            DatagramPacket dp=new DatagramPacket(bytes, bytes.length,ByName,port);
            //发送数据
            ds.send(dp);
        }
        ds.close();


    }
}
class send{
    public send() throws SocketException, UnknownHostException {

        DatagramSocket ds=new DatagramSocket();
        //打包数据
        boolean judge=true;
        while (judge){
            Scanner scanner=new Scanner(System.in);
            System.out.print("请你输入要发送的内容:");
            String Receive=scanner.next();
            if (Receive.equals("886")){
                break;
            }
            byte[] bytes = Receive.getBytes();
            //指定ip
            InetAddress ByName = InetAddress.getByName("255.255.255.255");
            //端口号
            int port=18895;
            DatagramPacket dp=new DatagramPacket(bytes, bytes.length,ByName,port);
        }
        ds.close();
    }
}
class receive{
    public receive() throws IOException {
        //创建接收端
        DatagramSocket ds=new DatagramSocket(18895);
        while (true) {
            //创建一个箱子接收
            byte[] bytes = new byte[1024];
            DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
            ds.receive(dp);
            //数据解析
            byte[] data = dp.getData();
            InetAddress address = dp.getAddress();
            int port = dp.getPort();
            int length = dp.getLength();
            System.out.println("该数据为:" + new String(data, 0, length));
            System.out.println("该数据是从IP为:" + address + "端口为:" + port + "发出来的");
        }
    }
}
